<?php

require_once(PLUGIN_DIR . 'Config.php');
class Image {
    private static $imageSize = array(
        'small' => array(120,90),
        'normal' => array(320,270),
        'big' => array(640,960)
    );

    public static function  makeImage($name,$path){
        foreach(Image::$imageSize as $item){
            $image = wp_get_image_editor($path);
            if(!is_wp_error($image)){
                $image->resize($item[0],$item[1],true);
                $imageName = explode(".",$name);
                $image->save(str_replace($name,$imageName[0]."-{$item[0]}x{$item[1]}.".$imageName[1],$path));
            }else{
                return false;
            }
        }
        return true;
    }

    public static function getImage($path,$size){
        switch($size){
            case "small":
                $formatPath = Image::formatImageName($path,"small");
                if(file_exists(Image::get_home_path().$formatPath)){
                    return $formatPath;
                }
            case "normal":
                $formatPath = Image::formatImageName($path,"normal");
                if(file_exists(Image::get_home_path().$formatPath)){
                    return $formatPath;
                }
            case "big":
                $formatPath = Image::formatImageName($path,"big");
                if(file_exists(Image::get_home_path().$formatPath)){
                    return $formatPath;
                }
            default:
                return $path;
        }
    }

    private static function get_home_path() {
        $home    = set_url_scheme( get_option( 'home' ), 'http' );
        $siteurl = set_url_scheme( get_option( 'siteurl' ), 'http' );
        if ( ! empty( $home ) && 0 !== strcasecmp( $home, $siteurl ) ) {
            $wp_path_rel_to_home = str_ireplace( $home, '', $siteurl ); /* $siteurl - $home */
            $pos = strripos( str_replace( '\\', '/', $_SERVER['SCRIPT_FILENAME'] ), trailingslashit( $wp_path_rel_to_home ) );
            $home_path = substr( $_SERVER['SCRIPT_FILENAME'], 0, $pos );
            $home_path = trailingslashit( $home_path );
        } else {
            $home_path = ABSPATH;
        }

        return str_replace( '\\', '/', $home_path );
    }


    private static function formatImageName($path,$size){
        $name = end(explode("/",$path));
        $nameArray = explode(".",$name);
        $imageSize = Image::$imageSize[$size];
        return str_replace($name,$nameArray[0]."-{$imageSize[0]}x{$imageSize[1]}.".$nameArray[1],$path);
    }
} 