module Gitea
  class UpdateFileInteractor
    def self.call(token, owner, params={})
      interactor = new(token, owner, params)
      interactor.run
      interactor
    end

    attr_reader :error, :result

    def initialize(token, owner, params)
      @owner   = owner
      @token   = token
      @params = params
    end

    def success?
      @error.nil?
    end

    def result
      @result
    end

    def run
      Contents::UpdateForm.new(valid_params).validate!
      response = Gitea::Repository::Entries::UpdateService.new(token, owner, @params[:identifier], file_path, file_params).call
      render_result(response)
    rescue Exception => exception
      fail!(exception.message)
    end

    private

    attr_reader :params, :owner, :token

    def fail!(error)
      puts "[exception]: error"
      @error = error
    end

    def render_result(response)
      if response.status == 200
        @result = JSON.parse(response.body)
      else
        Rails.logger.error("Gitea::Repository::Entries::UpdateService error[#{response.status}]======#{response.body}")
        @error = "更新失败，请确认该分支是否是保护分支。"
      end
    end

    def file_path 
      if @params[:base64_filepath].present? 
        Base64.decode64(params[:base64_filepath])
      else 
        @params[:filepath]
      end
    end

    def from_file_path 
      if @params[:base64_from_path].present? 
        Base64.decode64(params[:base64_from_path])
      else 
        @params[:from_path]
      end
    end

    def valid_params
      {
        filepath: file_path,
        branch: @params[:branch],
        new_branch: @params[:new_branch],
        sha: @params[:sha]
      }
    end

    def file_params
      Hash.new.merge(
        branch: @params[:branch],
        sha: @params[:sha],
        new_branch: @params[:new_branch],
        from_path: from_file_path,
        message: @params[:message],
        content: Base64.encode64(@params[:content])
      ).compact
    end
  end
end
