package phonenumber

import (
	"errors"
	"strings"
)

// Number takes a number and validates it
func Number(num string) (string, error) {
	num = strings.Map(func(r rune) rune {
		if r >= '0' && r <= '9' {
			return r
		}
		return -1
	}, num)
	// A number can be 11 digits long, if it starts with a 1
	// but ignore that one.
	if len(num) == 11 && num[0] == '1' {
		num = num[1:]
	}
	if len(num) != 10 {
		return "", errors.New("Invalid Number")
	}
	return num, nil
}

// AreaCode takes a number, validates it, and returns the area code
func AreaCode(num string) (string, error) {
	num, err := Number(num)
	if err != nil {
		return "", err
	}
	return num[:3], nil
}

// Format takes a number, validates it and returns it in the format
// (nnn) nnn-nnnn
func Format(num string) (string, error) {
	num, err := Number(num)
	if err != nil {
		return "", err
	}
	return "(" + num[:3] + ") " + num[3:6] + "-" + num[6:], nil
}
