class Api::V1::Users::OpenkylinSign::CreateService < ApplicationService
  include ActiveModel::Model 

  attr_reader :observe_user, :login, :email, :nickname, :phone, :address 

  # validates :login, format: {with: CustomRegexp::LOGIN}
  validates :email, format: {with: CustomRegexp::EMAIL}
  validates :nickname, length: { maximum: 32 }
  validates :phone, format: {with: CustomRegexp::PHONE}
  validates :address, length: { maximum: 100 }

  def initialize(observe_user, params={})
    @observe_user = observe_user
    @login = observe_user.login
    @email = params[:email]
    @nickname = params[:nickname]
    @phone = params[:phone]
    @address = params[:address]
  end

  def call 
    raise Error, errors.full_messages.join(",") unless valid?
    raise Error, '用户已经签署CLA协议！' if @observe_user.sign_cla
    begin
      ActiveRecord::Base.transaction do
        create_openkylin_sign_detail 
        update_user_sign_cla
      end
      
      return true
    rescue 
      raise Error, "服务器错误，请联系系统管理员！"
    end
  end

  private 
  def create_openkylin_sign_detail 
    OpenkylinSignDetail.create!(user_id: @observe_user.id, login: @login, email: @email, nickname: @nickname, phone: @phone, address: @address)
  end

  def update_user_sign_cla 
    @observe_user.update_attributes!(sign_cla: true)
  end
  
end