<?php

class ColorService
{

    private $site;
    private $commonColor;
    private $apiKey = '';
    private $colorData = [
        'screenshot_file' => '',
        'color_palette'   => []
    ];

    public function __construct($site, $commonColor, $apiKey = '')
    {
        $this->apiKey = $apiKey;
        $this->site = $site;
        $this->commonColor = $commonColor;
    }

    public function get()
    {
        if($this->takeScreenShot()){
            $this->colorAnalyze();
        }

        return $this->colorData;
    }

    private function takeScreenShot()
    {
        $ready = false;

        if($this->apiKey){
            $requestUrl = 'http://api.pagepeeker.com/v2/thumbs.php?size=l&refresh=1&code=' . $this->apiKey . '&url=' . $this->site;
            $readyUrl   = 'http://api.pagepeeker.com/v2/thumbs_ready.php?size=l&code=' . $this->apiKey . '&url=' . $this->site;
            $copyUrl    = 'http://api.pagepeeker.com/v2/thumbs.php?size=l&code=' . $this->apiKey . '&url=' . $this->site;
        }else{
            $requestUrl = 'http://free.pagepeeker.com/v2/thumbs.php?size=l&url=' . $this->site;
            $readyUrl   = 'http://free.pagepeeker.com/v2/thumbs_ready.php?size=l&url=' . $this->site;
            $copyUrl    = 'http://free.pagepeeker.com/v2/thumbs.php?size=l&url=' . $this->site;
        }

        file_get_contents_curl($requestUrl);

        Log::debug($requestUrl);

        for($i=0; $i<=20; $i++){

            $isReadyCall = file_get_contents_curl($readyUrl);

            if($isReadyCall === false){
                return false;
            }
            $isReady = json_decode($isReadyCall);

            if($isReady && $isReady->IsReady){
                $ready = true;
                break;
            }

            //Log::debug($isReady);
            //Log::debug($isReadyCall);
            sleep(2);
        }

        Log::debug($ready);

        if($ready){

            $file = md5($this->site);
            $copyFile = @copy($copyUrl, public_path('screenshots/' . $file . '.png'));

            if($copyFile){
                $this->colorData['screenshot_file'] = $file;
                return true;
            }
        }
        return false;
    }

    private function colorAnalyze()
    {
        $colorData = $this->commonColor->Get_Color(public_path('screenshots/' . md5($this->site) . '.png'), 21, true, true, 24);

        if($colorData){
            $this->colorData['color_palette'] = $colorData;
        }
    }


}