class Site

def catchall

def catchall
  create({
           domain: '',
           name: 'default_site',
           base_domain: 'localhost',
           homepage: Page.find_by_parent_id(nil),
         })
end

def create_homepage

def create_homepage
  if homepage_id.blank?
    self.homepage = build_homepage(title: "#{name} Homepage",
                                   slug: name.to_slug.to_s, breadcrumb: 'Home')
    default_status = TrustyCms::Config['defaults.page.status']
    homepage.status = Status[default_status] if default_status
    default_parts = TrustyCms::Config['defaults.page.parts'].to_s.strip.split(/\s*,\s*/)
    default_parts.each do |name|
      homepage.parts << PagePart.new(name: name, filter_id: TrustyCms::Config['defaults.page.filter'])
    end
    save
  end
end

def default

def default
  find_by_domain('') || find_by_domain(nil) || catchall
end

def dev_url(path = '/')

def dev_url(path = '/')
  uri = URI.join("http://#{TrustyCms::Config['dev.host'] || 'dev'}.#{base_domain}", path)
  uri.to_s
end

def find_for_host(hostname = '')

def find_for_host(hostname = '')
  return default if hostname.blank?
  sites = includes(:homepage).where('domain IS NOT NULL')
  site = sites.find { |site| hostname == site.base_domain || hostname =~ Regexp.compile(site.domain) }
  site || default
end

def reload_routes

def reload_routes
  TrustyCms::Application.reload_routes!
end

def several?

def several?
  several = (count > 1) if several.nil?
end

def url(path = '/')

def url(path = '/')
  uri = URI.join("http://#{base_domain}", path)
  uri.to_s
end