<?php


class Amazon extends MY_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->database();        
        $this->load->library('RestCrawlerServiceClient', [], 'restClient');
        $this->load->model('DSAmazon_model', 'amazon_model');
    }

    public function index()
    {
        $this->data = ['page' => $this->getPage(__FUNCTION__), 'categories' => $this->amazon_model->findAllCategories()];
        $this->load->view('page', $this->data);
    }

    public function all()
    {
        $data = $this->amazon_model->getTable(json_decode($this->input->raw_input_stream));
        $this->response($data);
    }

    public function delete()
    {
        $data = $this->restClient->deleteDeveloper(['developers' => array_column($this->input->post('selection'), 'id')]);
        $this->response(array(
            'code' => 200,
            'data' => []
        ));
    }

    public function update()
    {
        foreach ($this->input->post('selection') as $developer) {
            $this->restClient->updateDeveloper([
                'name' => $developer['name'],
                'description' => $developer['description'],
                'id' => $developer['id']
            ]);
        }
        $this->response(array(
            'code' => 200,
            'data' => []
        ));
    }

    public function save()
    {
        if ($this->restClient->saveDeveloper([
            'name' => $this->input->post('name'),
            'description' => $this->input->post('description')
        ])) {
            $this->response(array(
                'code' => 200,
                'data' => []
            ));
        } else {
            $this->response(array(
                'code' => 500,
                'data' => []
            ));
        }
    }

    public function coupang()
    { 
        $this->data = ['page' => $this->getPage(__FUNCTION__)];
        $this->load->view('page', $this->data);
    }

    public function coupang_all()
    {
        $data = $this->amazon_model->getTable(json_decode($this->input->raw_input_stream));
        $this->response($data);
    }

    public function add_asin($asinCode)
    {
        $asins = explode('-',$asinCode);
        if(count($asins) > 1) {
            $res = $this->restClient->getProductByBatchAsinCode(['asins' => $asins]);   
            $data = $res->data;
            foreach($data as $d) {
                $res->data = $d;
                $this->amazon_model->save($res);
            }
        }else {
            $res = $this->restClient->getProductByAsinCode($asinCode);          
            $this->amazon_model->save($res); 
        }
        
        $this->response(array(
            'code' => 200,
            'data' => $res->data->price
        ));
    }
}
