<?php

namespace App\Geo\Postal;

use \App\Core\Template\Output as Output;
use \App\Geo\State\Classes\State as State;
use \App\Geo\Postal\Classes\Postal as Postal;
use App\Geo\City\Classes\City;

//Facades
use ORM\DBInstance;

class PostalController
{

    /**
     * Index
     *   Show the main Postal list
     */
    function index()
    {
        $list = array();

        for ($i = 0; $i <= 10; $i++) {
            $obj = array();
            $obj['id'] = $i;
            $obj['value'] = md5($i);
            $obj['description'] = sha1($i);
            $list[] = $obj;
        }
        Output::render('index', array('list' => $list));
    }

    /**
     * Create
     *
     * Render the main Postal formulary
     */
    function create()
    {
        Output::setView('form', ['id' => 0]);
        Output::render();
    }

    /**
     * Store
     *
     * Store the param on the database
     * @param Postal $postal
     */
    function store(Postal $postal)
    {
    }

    /**
     * Search
     *
     * Store the param on the database
     * @param Postal $postal
     */
    function search($code)
    {

        //Search database for the record
        if ($json = DBInstance::getRecord('geo_postal_caches', ['code' => ['=', $code]])) {
            $json = json_decode(stripslashes($json[0]->json));
            $json->cached = true;
        } else {
            $json = json_decode(file_get_contents('https://viacep.com.br/ws/' . $code . '/json'));
        }

        //Respond with errror if fail #TODO add message
        if (!$json) {
            http_response_code(404);
            return;
        }

        $state = State::findOne(['shortname' => ['=', $json->uf]]);
        $json->state = $state->id;

        if (!$json->cached) {
            $record = [];
            $record['code'] = $code;
            $record['json'] = addslashes(json_encode($json));
            DBInstance::insertRecord('geo_postal_caches', $record);
        } else {
            return \RR\Response::json($json)->send();
        }

        if (!$city = City::findOne(['code' => ['=', $json->ibge]])) {
            $city = new City();
            $city->state_id = $state->id;
            $city->country_id = $state->country_id;
            $city->code = $json->ibge;
            $city->name = $json->localidade;
            $city->save();
        }

        if (!$postal = Postal::findOne(['code' => ['=', $code]])) {
            $postal = new Postal();
            $postal->country_id = $state->country_id;
            $postal->state_id = $state->id;
            $postal->city_id = $city->id;
            @$postal->road = $json->road;
            $postal->code = preg_replace('/[^0-9]/is', '', $json->cep);
            $postal->description = $json->complemento;
            $postal->save();
        }

        return \RR\Response::json($json)->send();
    }

    /**
     * Show    *
     * Render one register
     *
     * @param Postal $postal
     */
    function show(Postal $postal)
    {
    }

    /**
     * Edit
     *
     * Render the formular for a database Postal
     *
     * @param Postal $postal
     */
    function edit(Postal $postal)
    {
        Output::render('form', $postal);
    }

    /**
     * Update
     * Store the changes of the param on the database
     *
     * @param Postal $postal
     */
    function update(Postal $postal)
    {
    }

    /**
     * Destroy
     * If the object has soft delete.
     *
     * @param Postal $postal
     */
    function destroy(Postal $postal)
    {
    }

    /**
     * Purge
     * Remove object even with soft delete.
     *
     * @param Postal $postal
     */
    function purge(Postal $postal)
    {
    }

    public static function searchAndCreate($code)
    {
        $code = preg_replace('/[^0-9]/is', '', $code);

        if ($postal = Postal::findOne(['code' => ['=', $code]])) {
            return $postal;
        }

        //Search database for the record of load the database
        if ($json = DBInstance::getRecord('geo_postal_caches', ['code' => ['=', $code]])) {
            $json = json_decode(stripslashes($json[0]->json));
            $json->cached = true;
        } else {
            $json = json_decode(file_get_contents('https://viacep.com.br/ws/' . $code . '/json/unicode'));
        }

        $state = State::findOne(['shortname' => ['=', $json->uf]]);

        $json->state = $state->id;

        if (!$json->cached) {
            $record = [];
            $record['code'] = $code;
            $record['json'] = addslashes(json_encode($json));
            DBInstance::insertRecord('geo_postal_caches', $record);
        }

        if (!$city = City::findOne(['code' => ['=', $json->ibge]])) {
            $city = new City();
            $city->state_id = $state->id;
            $city->country_id = $state->country_id;
            $city->code = $json->ibge;
            $city->name = $json->localidade;
            $city->save();
        }

        if (!$postal = Postal::findOne(['code' => ['=', $code]])) {
            $postal = new Postal();
            $postal->country_id = $state->country_id;
            $postal->state_id = $state->id;
            $postal->city_id = $city->id;
            $postal->road = $json->logradouro;
            $postal->code = preg_replace('/[^0-9]/is', '', $json->cep);
            $postal->description = $json->complemento;
            $postal->save();
        }

        return $postal;
    }

    public static function fixPostal($postal)
    {
        $json = DBInstance::getRecord('geo_postal_caches', ['code' => ['=', $postal->code]]);
        $json = json_decode(stripslashes($json[0]->json));

        $city = City::findOne(['code' => ['=', $json->ibge]]);

        $postal->code = preg_replace('/[^0-9]/is', '', $json->cep);
        $postal->city_id = $city->id;
        $postal->state_id = $city->state_id;
        $postal->country_id = $city->country_id;
        $postal->save();

        return $postal;
    }
}
