require 'net/http'
require 'uri'

class PageService

    def self.get_deploykey()
        @deploy_key = EduSetting.find_by_name("site_page_deploy_key").try(:value)
        @deploy_domain = EduSetting.find_by_name("site_page_deploy_domain").try(:value)
    end

    
    def self.genernate_user(user_id)
        get_deploykey()
        Rails.logger.info "################### PageService genernate_user #{user_id}"
        user = User.find user_id
        if user.id_card_verify == true && user.website_permission == true
            uri = URI.parse("http://gitlink.#{@deploy_domain}/gitlink_execute_script?key=#{@deploy_key}&script_path=create_dir&owner=#{user.login.downcase}")
            response = Net::HTTP.get_response(uri)
        end
        Rails.logger.info "################### PageService genernate_user end #{response.body}"
        return response.body
    end

    def self.close_site(user_id,identifier=nil)
        get_deploykey()
        Rails.logger.info "################### PageService close_site #{user_id} / #{identifier}"
        user = User.find user_id
        uri = if identifier.present?
            URI.parse("http://gitlink.#{@deploy_domain}/gitlink_execute_script?key=#{@deploy_key}&script_path=remove_dir&owner=#{user.login.downcase}/*")
        else
            URI.parse("http://gitlink.#{@deploy_domain}/gitlink_execute_script?key=#{@deploy_key}&script_path=remove_dir&owner=#{user.login.downcase}/")
        end
        response = Net::HTTP.get_response(uri)
        Rails.logger.info "################### PageService close_site end #{response.body}"
        return response.body
    end

    def self.deploy_page(branch, page_id)
        get_deploykey()
        Rails.logger.info "################### PageService deploy #{branch} for page #{page_id}"
        page = Page.find page_id
        user = page.user
        project = page.project
        owner = user.login.downcase
        
        project_dir = page.identifier
        repo_link = project.repository.url
        repo = project.repository.identifier
        branch = branch
        script_path = branch == "gh-pages" ? "files_build" : page.build_script_path
        if script_path.present? 
            uri = URI.parse("http://gitlink.#{@deploy_domain}/gitlink_execute_script?key=#{@deploy_key}&script_path=#{script_path}&project_dir=#{project_dir}&repo=#{repo}&repo_link=#{repo_link}&branch=#{branch}&owner=#{owner}")
            response = Net::HTTP.get_response(uri)
            Rails.logger.info "################### PageService deploy  #{response.body}"
            return response.body
        end
    end 
end