<?php

namespace App\Http\Controllers;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
use Illuminate\Support\Str;


use App\Models\Modelo;
use App\Models\Registro;
use App\Models\RegistroMes;
use GIFEndec\Events\FrameDecodedEvent;
use GIFEndec\IO\FileStream;
use GIFEndec\Decoder;
use DB;
use Carbon\Carbon;
use Illuminate\Support\Facades\Redirect;


class ApiController extends Controller
{
    //INFORMACION DE LA ULTIMA ACTUALIZACION
    public function index(Request $request)
    {
        $modelosTotales = Modelo::where('activo', 1)->count();

            $modeloUltimo  = Modelo::all();
            $modeloUltimo  = $modeloUltimo->last()->created_at->toDateString();
            $modeloUltimo  ? $modeloUltimo : null;

        return array(
            'total_models'  =>    $modelosTotales,
            'last_update'   =>    $modeloUltimo
            
        );
    }

    //JSON CON DATOS DEL MODELO
    public function get_model($id)
    {
       $modelo = Modelo::where('activo', 1)->findOrFail($id);
       $slug = Str::slug($modelo->name, '_');
    
       return [
            "id"=>$modelo->id,   
            "type"=>$modelo->type,   
            "target"=>config('app.url').'/ver/target/'.$modelo->id,         
            "model"=>config('app.url').'/ver/modelo/'.$modelo->id
        ];
    }

    //JSON QUE SE GUARDARA EN LA APP
    public function get_model_json($id)
    {
       $modelo = Modelo::where('activo', 1)->findOrFail($id);
       $slug = Str::slug($modelo->name, '_');
    
       return [
            "name"=>$modelo->id,   
            "type"=>$modelo->type,   
            "version"=>$modelo->updated_at->toDateString(), 
            "extension"=>$modelo->extension, 
        ];
    }

    //INFORMACION DE TODAS LAS TARGETS
    public function targets(){
        $modelos = Modelo::
            where('activo', 1)
            ->where('private', 0)
            ->orderBy('id', 'asc')
            ->get();

        foreach($modelos as $modelo){

            $array[] = 
                [
                    'id'        =>  $modelo['id'],
                    'type'      =>  $modelo['type'],
                    'name'      =>  $modelo['name'],
                    'target'    =>  $modelo['target'],
                    "model"     =>config('app.url').'/ver/modelo/'.$modelo['id']
                    
                ]
            ;            
        }
        //$modelos['model'] = $modelos
        //return array("targets" => $array);
        return $array;
    }

    public function anuncio(){
        $anuncio = array(
            [
                'type'      =>  'video',
                'content'   =>  'https://www.youtube.com/watch?v=IQci9HaP-lA'
            ],
            [
                'type'      =>  'web',
                'content'   =>  '<h1>Hello word</h1>'
            ],
            [
                'type'      =>  'image',
                'content'   =>  'https://chinacoupon.info/wp-content/uploads/2015/12/bestprice400.png',
                'go_to'     =>  'http://uawa.ec/'
            ]
        );

        $aleatorio=array_rand($anuncio,1);

        return $anuncio[$aleatorio];
    }

    public function create(){
        return view('api_model');
    }

    public function store(Request $request){

        $this->validate($request, [
            'name'  =>  'required|string',
            'target' => 'required|image|max:2048',
            'model'    =>  'required|mimes:fbx,gif,mp4'
        ]);

        $modelo = new Modelo;
        $modelo->name = $request->get('name');

        //SABER ULTIMO ID
        $ultimoID = Modelo::all();
        $ultimoID = $ultimoID->last()->id+1;
        $url = 'https://s3.' . env('AWS_DEFAULT_REGION') . '.amazonaws.com/' . env('AWS_BUCKET') . '/';
        $slug = Str::slug($request->get('name'), '_');

        global $ultimoID, $slug;
        //SUBIR TARGET
            $target = $request->file('target');
            $filePathTarget = 'targets/' . $ultimoID.'_'.$slug.'.'.$target->getClientOriginalExtension();
            Storage::disk('s3')->put($filePathTarget, file_get_contents($target));
            $modelo->target = $url.$filePathTarget;
        

        $model= $request->file('model');
        switch ($model->getClientOriginalExtension()) {
            case 'gif':
                //SUBIR MODEL
                $model= $request->file('model');
                /**
                 * Open GIF as FileStream
                 */
                $gifStream = new FileStream($model);

                /**
                 * Create Decoder instance from MemoryStream
                 */
                $gifDecoder = new Decoder($gifStream);

                /**
                 * Run decoder. Pass callback function to process decoded Frames when they're ready.
                 */
                $gifDecoder->decode(function (FrameDecodedEvent $event) {
                    global $ultimoID, $slug;

                    /**
                     * Convert frame index to zero-padded strings (001, 002, 003)
                     */
                    $paddedIndex = str_pad($event->frameIndex, 3, '0', STR_PAD_LEFT);

                    /**
                     * Write frame images to directory
                     */
                   // $event->decodedFrame->getStream()->copyContentsToFile(__DIR__ . "/".$ultimoID.'_'.$slug."/frame{$paddedIndex}.png");


                    $archivo = $event->decodedFrame->getStream()->getContents();
                    $filePathModel = 'models/' . $ultimoID.'_'.$slug.'/'.$paddedIndex.'.png';
                    Storage::disk('s3')->put($filePathModel, $archivo);
                    


                    // Or get binary data as string:
                    // $frame->getStream()->getContents()

                    /**
                     * You can access frame duration using Frame::getDuration() method, ex.:
                     */
                    //$duracion = $event->decodedFrame->getDuration();
                   // $frameee = $event->frameIndex;
                });

                
                $framesTotales = Storage::disk('s3')->allFiles('models/' . $ultimoID.'_'.$slug);
                
            break;

            case 'mp4';
                //SUBIR MODEL
                $filePathModel = 'models/' . $ultimoID.'_'.$slug.'.'.$model->getClientOriginalExtension();
                Storage::disk('s3')->put($filePathModel, file_get_contents($model));
                $modelo->model = $url.$filePathModel;
            break;
            
            default:
                //SUBIR MODEL
                $filePathModel = 'models/' . $ultimoID.'_'.$slug.'.'.$model->getClientOriginalExtension();
                Storage::disk('s3')->put($filePathModel, file_get_contents($model));
                $modelo->model = $url.$filePathModel;
            break;
        }




        $modelo->type = $model->getClientOriginalExtension();
        
        $modelo->private = 0;
        $modelo->activo = 1;
        $modelo->save();

        //return $modelo;


        return $modelo;
    }


    //http://vultur-ar/ver/modelo/2_espoli
    //FUNCION QUE REDIRIGE A URL DE AMAZON Y CONTEA LAS VISUALIZACIONES EN EL SISTEMA
    public function ver(Request $request, $tipo, $idModelo){
    
        //CREA REGISTRO DEL MES PASADO
        $this->registro_mensual();

        //LOCALIZA IP DE CLIENTE
        /*
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } else
        */
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }

        //BUSCA SI LA IP Y EL MODELO EL DIA ACTUAL FUE ESCANEADO ALGUNA VEZ
        $ipExiste =  Registro::where('ip',$ip)->where('modelo',$idModelo)->whereDate('fecha', DB::raw('CURDATE()'))->count();

        //BUSCA EL MODELO PARA OBTENER LOS DATOS
        $url = Modelo::where('id', $idModelo)->firstOrFail();

        //OBTIENE INFORMACION DE LA IP
        $client = new \GuzzleHttp\Client();
        $res = $client->get('http://api.ipstack.com/'.$ip.'?access_key=27c5e2f36d79ed5c19c1e7215ce9406f&format=1&hostname=1&language=es&security=1');
        $jsonData = (string) $res->getBody();
        $jsonData = json_decode($jsonData);

        //return $jsonData->ip;
        //SI EN LA URL SE ESPECIFICA EL TIPO MODELO
        if($tipo == "modelo"){

            //SI LA IP EXISTE YA EN LA DB Y HAY MAS DE 
            if($ipExiste > 0){
                //SI YA ESCANEO ALGUNA EL DIA DE HOY SUMA UNA VISUALIZACION
                $actualiza = Registro::where('ip',$ip)->where('modelo',$idModelo)->whereDate('fecha', DB::raw('CURDATE()'))->firstOrFail();
                $actualiza->visualizaciones += 1;
                $actualiza->update();
                
            }else{
                //SI AUN NO VISUALIZA NINGUNA VEZ EL DIA DE HOY
                //CREA UN REGISTRO QUE SE VISUALIZO 
                $registro = new Registro;
                $registro->ip = $ip;
                $registro->modelo = $idModelo;
                $registro->continente = $jsonData->continent_name ?? null;
                $registro->pais = $jsonData->country_name ?? null;
                $registro->provincia = $jsonData->region_name ?? null;
                $registro->ciudad = $jsonData->city?? null;
                $registro->codigoPostal = $jsonData->zip ?? null;
                $registro->latitud = $jsonData->latitude ?? null;
                $registro->longitud = $jsonData->longitude ?? null;
                $registro->save();
            }


            return Redirect::to($url->modelo);
        }else{
            //SI SE ESPECIFICA TIPO TARGET
            //DEVUELVE URL DE IMAGEN DIRECTAMENTE SIN CONTABILIZAR VISUALIZACION
            return Redirect::to($url->target);
        }


        //PARA VER es http://vultur-ar/ver/modelo/2_espoli
    }

    //CREA REGISTRO MENSUAL
    public function registro_mensual(){
        //OBTINE ULTIMO DIA DEL MES PASADO
        setlocale(LC_ALL, 'es_ES');
        $fecha = new Carbon('last day of last month');
        $fechaUno = new Carbon('first day of last month');

        //CUENTA SI HAY REGISTROS DEL MES
        $existeRegistro =  RegistroMes::where('anyo',$fecha->format('Y'))
        ->where('mesNumero',$fecha->format('m'))
        ->count();

        
        if($existeRegistro == 0){
            //SI NO EXISTE NINGUN REGISTRO

            //OBTIENE CONTEO DEL MES PASADO
            $escaneosMes = Registro::whereBetween('fecha', [$fechaUno, $fecha->endOfMonth()])->sum('visualizaciones');
   
            //CREA UN REGISTRO DEL MES PASADO
            $registro = new RegistroMes;
            $registro->escaneosTotales = $escaneosMes;
            $registro->mesNombre = $fecha->formatLocalized('%B');
            $registro->mesNumero = $fecha->format('m');
            $registro->anyo = $fecha->format('Y');
            $registro->fecha = $fecha->format('Y-m-d');
            $registro->save();            
        }
    }

}
