<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Maptoon_lib {

	var $file_cache_path = '';
	var $CI = null;
	private $db;

	public function __construct($params) {
		if(isset($params['file_cache_path'])==TRUE && $params['file_cache_path']!='') {
			$this->file_cache_path = $params['file_cache_path'];
		}
		$this->CI = &get_instance();
		$this->db = &$this->CI->db;
		$this->load = &$this->CI->load;
	}

	/*
	write category cache file
	@param (numeric) maptoon category table idx
	@param (string) episode data by category idx
	@return (boolean)
	 */
	public function write_category_cache($cid,$json_data) {
		if(is_numeric($cid)==FALSE || $cid<=0) {
			return FALSE;
		}
		$this->CI->load->helper('file');
		$fname = $this->get_category_cache_name($cid);
		if($fname!='') {
			return write_file($fname, $json_data, 'w');		
		} else {
			return FALSE;
		}
	}

	public function get_category_cache($cid) {
		return $this->getEpisodeCategory($cid);
		if(is_numeric($cid)==FALSE || $cid<=0) {
			return FALSE;
		}
		$this->CI->load->helper('file');
		$fname = $this->get_category_cache_name($cid);
		if($fname!='') {
			return read_file($fname);		
		} else {
			return FALSE;
		}
	}

	/*
	get category cache file name
	@param (numeric) maptoon category table idx
	@return (string | null)
	 */
	public function get_category_cache_name($cid) {
		if(is_numeric($cid)==TRUE && $cid>0) {
			$fname = $this->file_cache_path.'category'.$cid;
			return $fname;
		} else {
			return '';
		}
	}

	public function getEpisodeCategory($categoryId) {
        $query = "SELECT idx,mt_episodes_idx FROM mt_categories where idx=$categoryId";
        $result = $this->db->query($query);
        foreach ($result->result_array() as $row){
            $episodes_idx = explode(",",$row['mt_episodes_idx']);
            $str = $row['mt_episodes_idx'];
            $idx = $row['idx'];

            $len = count($episodes_idx);

            if(is_array($episodes_idx)==TRUE && is_numeric($idx)==TRUE 
                && $idx>0 && $len>0) {
				$this->load->model('maptoon/m_maptoon');				
                $ret = $this->CI->m_maptoon->update_episodes_by_category($idx,$str);

                $this->CI->config->load('filecache',TRUE);
                $file_cache_path = $this->CI->config->item('file_cache_path','filecache');
                $params = array('file_cache_path'=>$file_cache_path);
                $this->load->library('maptoon_lib',$params);

                // get episode data to write cache
                return $this->CI->m_maptoon->get_widget_info_by_episode_idx($episodes_idx,'json');
            }
        }
	}
}