<?php

/**
 * @author owen
 *
 */
class Filemd5Model extends CI_Model{
    public static $appFolder = "";
    public $json = [];
    public $curPath = "";
    public function start($path,$filename) {
        self::$appFolder = $path;
        $destManifestPath = $filename;

        // dest file handle
        $manifestHandle = fopen ( $destManifestPath, "w+" );

        // write md5
        self::traverse ( $path );
        if (! fwrite($manifestHandle,json_encode($this->json,JSON_NUMERIC_CHECK))){
            return false;
        }
        // close file
        fclose ( $manifestHandle );
        return true;
    }

    /**
     * 获取活动md5信息
     */
    public function getActMd5Files($activityPath) {
        $path = APPPATH ."../public/game/image/activity_2/".$activityPath;
        self::$appFolder = $path;
        self::traverse ( $path , $activityPath);
        return $this->json;
    }

    /**
     * 遍历应用根目录下的文件，并生成对应的文件长度及md5信息
     * @param $AppPath
     * @return bool|void
     * Created by: Owen
     * Created on: 2020/7/6 19:49
     */
    public function traverse($AppPath, $prefix='') {
        if (! file_exists ( $AppPath )) {
            oo::logs()->debug3( $AppPath . " does not exist!" , 'md5.log');
            return;
        }
        if (! is_dir ( $AppPath )) {
            oo::logs()->debug3( $AppPath . " is not a directory!" , 'md5.log');
            return;
        }
        if (! ($dh = opendir ( $AppPath ))) {
            oo::logs()->debug3( "Failure while read diectory!" , 'md5.log');
            return;
        }

        while ( ($file = readdir ( $dh )) != false ) {
            $subDir = $AppPath . DIRECTORY_SEPARATOR . $file;
            if ($file == "." || $file == "..") {
                continue;
            } else if (is_dir ( $subDir )) {
                self::traverse ( $subDir , $prefix);
            } else {
                self::writeOneFieToManifest ( $subDir , $prefix);
            }
        }
        closedir ( $dh );
    }

    /**
     * 写一个文件的md5信息到文件中
     * @param $filePath
     * Created by: Owen
     * Created on: 2020/7/6 19:46
     */
    public function writeOneFieToManifest($filePath, $prefix = '') {
        if (! file_exists ( $filePath )) {
            return ;
        }
        $relativePath = str_replace ( self::$appFolder . DIRECTORY_SEPARATOR, '', $filePath );

        $relativePath = str_replace ( "\\", "/", $relativePath );
        if (strpos ( $relativePath, "tmp/" ) === 0) {
            return;
        }
        $relativePath = $prefix ? $prefix.'/'.$relativePath : $relativePath;
        $temp = [
            'fileName' => $relativePath,
            'md5'      => @md5_file ( $filePath ),
            'size'     => filesize ( $filePath ),
        ];
        $this->json[] = $temp;
    }

    /**
     * 設置静态配置文件
     * @param $configName
     * @param $filename
     * @return mixed
     * Created by: Owen
     * Created on: 2020/4/29 19:56
     */
    public function staticMd5Config($configName,$filename){
        $curFileName = oo::commonOprRedis('games')->hGet(okeys::StaticMd5Config(),$configName);
        if(!empty($curFileName)){
            $curFileMd5  = @md5_file(APPPATH ."../public/game/config/".$curFileName);
            $newFileMd5  = @md5_file(APPPATH ."../public/game/config/".$filename);
            if($curFileMd5 == $newFileMd5){
                return true;
            }
        }
        $tb  = otable::StaticMd5Config();
        $sql = "UPDATE {$tb} SET path='{$filename}' WHERE config='{$configName}'";
        $ret = oo::commonOprDb('games')->query($sql);
        $cache = oo::commonOprRedis('games')->hSet(okeys::StaticMd5Config(),$configName,$filename);
        return min($ret,$cache);
    }

    /**
     * 生成卡片md5
     * Created by: Owen
     * Created on: 2020/7/6 20:05
     */
    public function makeCardMd5(){
        $fileName = "card_md5".time().".json";
        self::start(APPPATH ."../public/game/image/newcard",APPPATH ."../public/game/config/".$fileName)
        && self::staticMd5Config("card",$fileName);
    }

    /**
     * 生成活動md5
     * Created by: Owen
     * Created on: 2020/7/6 20:05
     */
    public function makeActivityMd5(){
        $fileName = "activity_md5".time().".json";
        self::start(APPPATH ."../public/game/image/activity_2",APPPATH ."../public/game/config/".$fileName)
        && self::staticMd5Config("activity",$fileName);
    }

    /**
     * 生成SpineMd5
     * Created by: Owen
     * Created on: 2021/1/27 16:29
     */
    public function makeSpineMd5(){
        $fileName = "spine_md5".time().".json";
        self::start(APPPATH ."../public/game/spine",APPPATH ."../public/game/config/".$fileName)
        && self::staticMd5Config("spine",$fileName);
    }

    /**
     * 生成SpineMd5
     * Created by: Owen
     * Created on: 2021/1/27 16:29
     */
    public function makeMd5($name,$path){
        $fileName = $name."_md5".time().".json";
        self::start(APPPATH ."../public/game/".$path,APPPATH ."../public/game/config/".$fileName)
        && self::staticMd5Config($name,$fileName);
    }
}


?>
