class Api::V1::Users::Projects::ListService < ApplicationService
  include ActiveModel::Model

  attr_reader :observe_user, :category, :is_public, :project_type, :sort_by, :sort_direction, :search, :start_at, :end_at, :current_user
  attr_accessor :queried_projects

  validates :category, inclusion: {in: %w(all join created manage watched forked), message: "请输入正确的Category"}
  validates :is_public, inclusion: {in: [true, false], message: '请输入正确的IsPublic'}, allow_nil: true
  validates :project_type, inclusion: {in: %w(common mirror sync_mirror), message: '请输入正确的ProjectType'}, allow_nil: true
  validates :sort_by, inclusion: {in: Project.column_names, message: '请输入正确的SortBy'}
  validates :sort_direction, inclusion: {in: %w(asc desc), message: '请输入正确的SortDirection'}

  def initialize(observe_user, params, current_user=nil)
    @observe_user = observe_user
    @category = params[:category] || 'all'
    @is_public = ActiveModel::Type::Boolean.new.cast(params[:is_public])
    @project_type = params[:project_type]
    @sort_by = params[:sort_by] || 'updated_on'
    @sort_direction = params[:sort_direction] || 'desc'
    @search = params[:search]
    @start_at = params[:start_at]
    @end_at = params[:end_at]
    @current_user = current_user
  end

  def call 
    raise Error, errors.full_messages.join(", ") unless valid? 
    begin
      project_query_data

      queried_projects
    rescue 
      raise Error, "服务器错误，请联系系统管理员！"
    end
  end

  private 
  def project_query_data 
    if current_user.admin? || @observe_user.id == current_user.id
      projects = Project
    else
      projects = Project.visible 
    end

    case category 
    when 'join'
      normal_projects = projects.where.not(user_id: observe_user.id).members_projects(observe_user.id).to_sql 
      org_projects = projects.joins(team_projects: [team: :team_users]).where(team_users: {user_id: observe_user.id}).to_sql
      projects = Project.from("( #{normal_projects} UNION #{org_projects} ) AS projects").distinct 
    when 'created'
      projects = projects.where(user_id: observe_user.id)
    when 'manage'
      normal_projects = projects.joins(members: :roles).where(members: {user_id: observe_user.id}, roles: {name: 'Manager'}).to_sql 
      org_projects = projects.joins(team_projects: [team: :team_users]).where(team_users: {user_id: observe_user.id}, teams: {authorize: %w(owner admin)}).to_sql
      projects = Project.from("( #{normal_projects} UNION #{org_projects} ) AS projects").distinct 
    when 'watched'
      projects = projects.where.not(user_id: observe_user.id).joins(:watchers).where(watchers: {watchable_type: "Project", user_id: observe_user.id})
      projects = projects.joins(:watchers).where("watchers.created_at > ? and watchers.created_at < ?", Time.at(start_at.to_i), Time.at(end_at.to_i)) if start_at.present? && end_at.present?
    when 'only_watched'
      projects = projects.where.joins(:watchers).where(watchers: {watchable_type: "Project", user_id: observe_user.id})
      projects = projects.joins(:watchers).where("watchers.created_at > ? and watchers.created_at < ?", Time.at(start_at.to_i), Time.at(end_at.to_i)) if start_at.present? && end_at.present?
    when 'forked'
      if start_at.present? && end_at.present?
        fork_ids = observe_user.fork_users.where("created_at > ? and created_at < ?", Time.at(start_at.to_i), Time.at(end_at.to_i)).select(:id, :fork_project_id).pluck(:fork_project_id)
      else
        fork_ids = observe_user.fork_users.select(:id, :fork_project_id).pluck(:fork_project_id)
      end
      projects = projects.where(id: fork_ids)
    else
      normal_projects = projects.members_projects(observe_user.id).to_sql
      org_projects = projects.joins(team_projects: [team: :team_users]).where(team_users: {user_id: observe_user.id}).to_sql
      projects = Project.from("( #{ normal_projects} UNION #{ org_projects } ) AS projects").distinct
    end

    unless is_public.nil? 
      if is_public
        projects = projects.visible 
      else
        projects = projects.is_private
      end
    end
    

    projects = projects.with_project_type(project_type)

    # 表情处理
    search = search.to_s.each_char.select { |c| c.bytes.first < 240 }.join('')
    q = projects.ransack(name_or_identifier_cont: search)

    scope = q.result.includes(:project_category, :project_language,:owner, :repository, :has_pinned_users)


    scope = scope.order("projects.#{sort_by} #{sort_direction}")

    @queried_projects = scope
  end

end