class SitePagesController < ApplicationController
    before_action :require_login, except: [:softbot_build, :themes]
    before_action :require_profile_completed, only: [:create]
    before_action :load_project, except: [:softbot_build, :index, :themes]
    before_action :authenticate_user!, except: [:softbot_build, :index, :themes, :show]
    before_action :authenticate_member!, only: [:show]

    def index
        pages = PageQuery.call(params,current_user)
        @total_count = pages.size
        @pages = paginate(pages)
    end

    def show
        @page = Page.find_by(project_id: @project.id)
        return render_ok({data:nil}) unless @page.present?
    end
    
    def create
        return normal_status(-1, '你还未开通Page服务，无法进行部署') unless current_user.website_permission
        return normal_status(-1, '你已开通Page服务') if Page.exists?(user: current_user)
        return normal_status(-1, '该仓库已开通Page服务') if Page.exists?(project: @project)
        @page = Page.new(create_params)
        @page.user = current_user
        @page.project = @project
        @page.save
    end

    def update
        return normal_status(-1, '你还未开通Page服务') unless current_user.website_permission
        return normal_status(-1, '你还未开通Page站点') unless Page.exists?(user: current_user)
        @page = Page.find_by(user: current_user)
        @page.update(language_frame: params[:language_frame])
        render_ok
    end

    def build
        return normal_status(-1, '你还未开通Page服务，无法进行部署') unless current_user.website_permission
        return normal_status(-1, '该仓库还未开通Page服务，无法进行部署') unless Page.exists?(project: @project)
        @page = Page.find params[:id]
        return normal_status(-1, @page.state_description) unless @page.state
        response_str =  @page.deploy_page(params[:branch])
        data = JSON.parse(response_str)['result'] || (data = JSON.parse(response_str)['error'])
        if data.to_s.include?('部署成功')
            @page.update(last_build_at: Time.now, build_state: true, last_build_info: data)
        else
            @page.update(build_state:false, last_build_info: data)
        end
        render_ok({data: data.nil? ? nil : data.split("\n") })
    end

    def softbot_build
        branch = params[:ref].split('/').last
        user = User.find_by_login params[:repository][:owner][:login]
        return normal_status(-1, '你还未开通Page服务，无法进行部署') unless user.website_permission

        project = Project.find_by(identifier: params[:repository][:name],user_id: user.id)
        return normal_status(-1, '项目不存在') if project.nil?
        return normal_status(-1, '该仓库还未开通Page服务，无法进行部署') unless Page.exists?(user: user, project: project)

        @page = Page.find_by(user: user, project: project)
        response_str =  @page.deploy_page(branch)
        data = JSON.parse(response_str)['result']
        if data.nil?
            data = JSON.parse(response_str)['error']
        end
        
        if data.include?('部署成功')
            @page.update(last_build_at: Time.now, build_state: true, last_build_info: data)
        else
            @page.update(build_state:false, last_build_info: data)
        end
        render_ok
    end

    def themes
        # data =  YAML.load_file(Rails.root.join('config/admins', 'page_themes.yml'))
        # render_ok({themes:data[theme_params.downcase]})
        @themes = PageTheme.where(language_frame:theme_params).order(order_index: :asc)
    end

    private
    def authenticate_user!
        unless @project.manager?(current_user) || current_user.admin?
            return render_forbidden('你不是管理员，没有权限操作')
        end
    end

    def authenticate_member!
        unless @project.member?(current_user) || current_user.admin?
            return render_forbidden('你不是成员，没有权限操作')
        end
    end

    def theme_params
        params[:language_frame] || 'hugo'
    end

    def create_params
        params.permit(:identifier, :language_frame, :theme, :site_name)
    end
end
