#coding=utf-8

module JupyterService

    def _open_shixun_jupyter(shixun)
        if shixun.is_jupyter?
            shixun_tomcat = edu_setting('cloud_bridge')
            uri = "#{shixun_tomcat}/bridge/jupyter/get"
            tpiID = "tpm#{shixun.id}"
            mount = shixun.data_sets.present?
            gitUrl = "#{edu_setting('git_address_domain')}/#{shixun.repo_path}"
            params = {tpiID: tpiID, identifier: shixun.identifier, needMount: mount, gitUrl: gitUrl,
                      :containers => "#{Base64.urlsafe_encode64(shixun_container_limit(shixun))}"}
    
            logger.info "test_juypter: uri->#{uri}, params->#{params}"
            res = uri_post uri, params
            if res && res['code'].to_i != 0
                raise("实训云平台繁忙（繁忙等级：99）")
            end

            logger.info "test_juypter: #{res}"

            @shixun_jupyter_port = res['port']

            "#{jupyter_service(res['port'])}/notebooks/data/workspace/myshixun_#{tpiID}/01.ipynb"
        end
    end

    def jupyter_url_with_shixun(shixun)
        #打开tpm - juypter接口
        _open_shixun_jupyter(shixun)
    end

    def jupyter_port_with_shixun(shixun)
        if @shixun_jupyter_port.to_i <=0 
            _open_shixun_jupyter(shixun)
        end
        @shixun_jupyter_port
    end


    def _open_game_jupyter(myshixun)
        ## 打开tpi
        shixun = myshixun.shixun

        if shixun.is_jupyter?
            shixun_tomcat = edu_setting('cloud_bridge')
            uri = "#{shixun_tomcat}/bridge/jupyter/get"

            tpiID = myshixun.id
            mount = myshixun.shixun.data_sets.present?

            gitUrl = "#{edu_setting('git_address_domain')}/#{myshixun.repo_path}"
            params = { tpiID: tpiID, 
                       identifier: shixun.identifier,
                       myshixunIdentifier: myshixun.identifier,
                       gitUrl: gitUrl,
                       needMount: mount,
                       :containers => "#{Base64.urlsafe_encode64(shixun_container_limit(shixun))}"}
            res = uri_post uri, params

            logger.info "test_juypter: #{res}"
            
            if res && res['code'].to_i != 0
                raise("实训云平台繁忙（繁忙等级：99）")
            end

            @game_jupyter_port = res['port']

            repo_save_path = myshixun.repo_save_path

            "#{jupyter_service(res['port'])}/notebooks/data/workspace/myshixun_#{tpiID}/#{repo_save_path}/01.ipynb"
        end
    end


    def jupyter_url_with_game(myshixun)
        _open_game_jupyter(myshixun)
    end

    def jupyter_port_with_game(myshixun)
        if @game_jupyter_port.to_i <=0 
            _open_game_jupyter(myshixun)
        end
        @game_jupyter_port
    end

    def jupyter_save_with_shixun(shixun,jupyter_port)
        author_name = current_user.real_name
        author_email = current_user.git_mail
        message = "User submitted"

        tpiID = "tpm#{shixun.id}"

        src_url = "#{jupyter_service(jupyter_port)}/nbconvert/notebook/data/workspace/myshixun_#{tpiID}/01.ipynb?download=true"

        response = Faraday.get(src_url)

        if response.status.to_i != 200
            raise("获取文件内容失败：#{response.status}")
        end

        content = response.body.force_encoding('utf-8')
        
        c = GitService.update_file(repo_path: shixun.repo_path,
            file_path: "01.ipynb",
            message: message,
            content: content,
            author_name: author_name,
            author_email: author_email)

        return c.size
    end

    def jupyter_save_with_game(myshixun,jupyter_port)
        author_name = current_user.real_name
        author_email = current_user.git_mail
        message = "User submitted"

        tpiID = myshixun.id

        repo_save_path = myshixun.repo_save_path
        src_url = "#{jupyter_service(jupyter_port)}/nbconvert/notebook/data/workspace/myshixun_#{tpiID}/#{repo_save_path}/01.ipynb?download=true"
        response = Faraday.get(src_url)

        if response.status.to_i != 200
            raise("获取文件内容失败：#{response.status}")
        end

        content = response.body.force_encoding('utf-8')
        
        c = GitService.update_file(repo_path: myshixun.repo_path,
            file_path: "01.ipynb",
            message: message,
            content: content,
            author_name: author_name,
            author_email: author_email)

        return c.size
    end


    ##重置jupyter环境
    def jupyter_tpi_reset(myshixun)
        jupyter_delete_tpi(myshixun)
        url = jupyter_url_with_game(myshixun)
        port = jupyter_port_with_game(myshixun)
        {url: url, port: port}
    end

    ## 重置tpm环境
    def jupyter_tpm_reset(shixun)
        jupyter_delete_tpm(shixun)

        url = jupyter_url_with_shixun(shixun)
        port = jupyter_port_with_shixun(shixun)

        {url: url, port: port}
    end



    # 删除pod
    def jupyter_delete_tpi(myshixun) 
        myshixun_id = myshixun.id
        digest = myshixun.identifier + edu_setting('bridge_secret_key')
        digest_key = Digest::SHA1.hexdigest("#{digest}")
        begin
            shixun_tomcat = edu_setting('cloud_bridge')
            uri = "#{shixun_tomcat}/bridge/jupyter/delete"
            Rails.logger.info("#{current_user} => cloese_jupyter digest is #{digest}")
            params = {:tpiID => myshixun_id, :digestKey => digest_key, :identifier => myshixun.identifier}
            res = uri_post uri, params
            if res && res['code'].to_i != 0
                raise("实训云平台繁忙（繁忙等级：110）")
            end
        end
    end


    def jupyter_delete_tpm(shixun) 
        tpiID = "tpm#{shixun.id}"
        digest = shixun.identifier + edu_setting('bridge_secret_key')
        digest_key = Digest::SHA1.hexdigest("#{digest}")
        begin
            shixun_tomcat = edu_setting('cloud_bridge')
            uri = "#{shixun_tomcat}/bridge/jupyter/delete"
            Rails.logger.info("#{current_user} => cloese_jupyter digest is #{digest}")
            params = {:tpiID => tpiID, :digestKey => digest_key, :identifier => shixun.identifier}
            res = uri_post uri, params
            if res && res['code'].to_i != 0
                raise("实训云平台繁忙（繁忙等级：110）")
            end
        end
    end

    def jupyter_service jupyter_port
        edu_setting('jupyter_service').gsub("PORT", jupyter_port)
    end

    def _jupyter_active(tpiID)
        shixun_tomcat = edu_setting('cloud_bridge')
        uri = "#{shixun_tomcat}/bridge/jupyter/active"
        params = {:tpiID => tpiID}
        res = uri_post uri, params
        if res && res['code'].to_i != 0
            raise("实训云平台繁忙（繁忙等级：120）")
        end
    end

    # tpm 延时
    def jupyter_active_tpm(shixun)
        tpiID = "tpm#{shixun.id}"
        _jupyter_active(tpiID)
    end

    # tpi 延时
    def jupyter_active_tpi(myshixun)
      tpiID = myshixun.id 
        _jupyter_active(tpiID)
    end

    def _jupyter_timeinfo(tpiID)
        shixun_tomcat = edu_setting('cloud_bridge')
        uri = "#{shixun_tomcat}/bridge/jupyter/getTimeInfo"
        params = {:tpiID => tpiID}
        res = uri_post uri, params
        if res && res['code'].to_i != 0
            raise("实训云平台繁忙（繁忙等级：130）")
        end

        res['data']
    end

    # 获取时间参数
    def jupyter_timeinfo_tpm(shixun)
      tpiID = "tpm#{shixun.id}"
      _jupyter_timeinfo(tpiID)
    end

    # 获取时间参数
    def jupyter_timeinfo_tpi(myshixun)
      tpiID = myshixun.id 
      _jupyter_timeinfo(tpiID)
    end
end
