<?php
/**
 * @author: Jörg Reinholz, fastix Webdesign, Kassel http://www.fastix.org
 * @return string
 * @uses a dir with nice icons for mime-types of files
**/


class IconSelector
{
    protected $arIconFiles;
    protected $mimeIconsDir;

    public function __construct ( $mimeIconsDir ) {

        $DH = opendir( $_SERVER['DOCUMENT_ROOT'] . $mimeIconsDir ) or die('Konnte Icons-Dir nicht lesen');
        while ( $filename = readdir( $DH ) ) {
            $t = $filename[0];
            if ( '.' != $t ) {
                $arIconFiles[] = $filename;
            }
        }

        $this -> arIconFiles  = $arIconFiles;
        $this -> mimeIconsDir = $mimeIconsDir;
    }

    public function selectIcon( $mimeType ) {
        $mimeType    = str_replace( '/', '-x-', $mimeType );
        $defaultIcon = $this -> mimeIconsDir . 'gtk-file.svg';
        $arIconFiles = $this -> arIconFiles;
        foreach ($arIconFiles as $haystack) {
            if ( 0 === strpos($haystack, $mimeType) ) {
                return( $this -> mimeIconsDir . $haystack );
            }
        }
        $mimeType    = str_replace( '-x-', '-', $mimeType );
        $defaultIcon = '/mime-icons/gtk-file.svg';
        $arIconFiles = $this -> arIconFiles;
        foreach ( $arIconFiles as $haystack ) {
            if ( 0 === strpos( $haystack, $mimeType ) ) {
                return( $this -> mimeIconsDir . $haystack );
            }
        }

        $mimeTypeParts = explode( '-', $mimeType );
        $mimeTypeFirst = $mimeTypeParts[0];
        $mimeTypeLast  = $mimeTypeParts[count( $mimeTypeParts ) -1 ];

        foreach ( $arIconFiles as $haystack ) {
            if ( strpos( $haystack, '-' . $mimeTypeLast ) ) {
                return( $this -> mimeIconsDir . $haystack );
            }
        }

        foreach ( $arIconFiles as $haystack ) {
            if ( 0 === strpos( $haystack, $mimeTypeFirst ) ) {
                return( $this -> mimeIconsDir . $haystack );
            }
        }

        return $defaultIcon;
    }
}